package com.cskaoyan.mall.controller.mall;

import com.cskaoyan.mall.model.bo.goods.AskGoodsMsgBo;
import com.cskaoyan.mall.model.po.Type;
import com.cskaoyan.mall.model.vo.goods.*;
import com.cskaoyan.mall.model.vo.message.LeaveMessageVo;
import com.cskaoyan.mall.model.vo.message.QuestionAnswerVo;
import com.cskaoyan.mall.model.vo.order.OrderMessageVo;
import com.cskaoyan.mall.model.vo.user.UserMessageVo;
import com.cskaoyan.mall.service.lmpl.GoodsServiceImpl;
import com.cskaoyan.mall.service.lmpl.MessageServiceImpl;
import com.cskaoyan.mall.utils.GoodsResult;
import com.cskaoyan.mall.utils.Json;
import com.cskaoyan.mall.utils.Result;
import com.cskaoyan.mall.utils.UserResult;
import com.google.gson.Gson;
import org.apache.ibatis.executor.ResultExtractor;

import javax.naming.NameNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.List;

import static java.lang.Float.NaN;

/**
 * @ClassName: MallGoodsServlet
 * @Description: TODO
 * @Auther 庄左
 * @Date 2022/7/3 17:54
 * @Version
 **/
@WebServlet("/api/mall/goods/*")
public class MallGoodsServlet extends HttpServlet {

    //获取json字符串
    private String getJsonString(HttpServletRequest req) throws IOException {
        ServletInputStream inputStream = req.getInputStream();
        //写入字节数组的输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        //转为字符串
        return outputStream.toString("utf-8");
    }

    private Gson gson = new Gson();
    private Result result = new Result();
    private GoodsResult goodsResult = new GoodsResult();
    private UserResult userResult = new UserResult();
    private GoodsServiceImpl goodsService = new GoodsServiceImpl();
    Json json =new Json();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String replace = requestURI.replace(req.getContextPath() + "/api/mall/goods/", "");

        if ("askGoodsMsg".equals(replace)){
            askGoodsMsg(req,resp);
        }

    }

    private void askGoodsMsg(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        AskGoodsMsgBo askGoodsMsgBo = gson.fromJson(json.getJsonString(req), AskGoodsMsgBo.class);

        int i = goodsService.insertGoodsMsg(askGoodsMsgBo);
        if (i==0){
            result.setCode(10000);
            result.setMessage("提问失败，请稍后再试");
            resp.getWriter().println(gson.toJson(result));
            return;
        }
        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String replace = requestURI.replace(req.getContextPath() + "/api/mall/goods/", "");
        if ("getGoodsByType".equals(replace)) {
            getGoodsByType(req, resp);
        }
        if ("getGoodsInfo".equals(replace)) {
            getGoodsInfo(req, resp);
        }
        if ("getGoodsMsg".equals(replace)) {
            getGoodsMsg(req, resp);
        }
        if ("getGoodsComment".equals(replace)) {
            getGoodsComment(req, resp);
        }
        if ("searchGoods".equals(replace)){
            searchGoods(req,resp);
        }
    }

    /**
    * @Author: 庄左
    * @Description: 采用商品名称的模糊查询，在商品表查找
    * @DateTime: 2022/7/9 16:13
    */
    private void searchGoods(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String keyword = req.getParameter("keyword");
        List<GoodsSearchVo> goods = goodsService.selectGoodsByGoodsName(keyword);

        result.setCode(0);
        result.setData(goods);
        resp.getWriter().println(gson.toJson(result));
    }


    /**
     * @Author: 庄左
     * @Description: 根据商品id查找该商品的所有评论
     * @DateTime: 2022/7/4 9:00
     */
    private void getGoodsComment(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer goodsId = Integer.valueOf(req.getParameter("goodsId"));

        List<CommentVo> comment = goodsService.selectGoodsCommentByGoodsId(goodsId);
        double score = 0;
        int count = 0;
        for (CommentVo commentVo : comment) {
            score = commentVo.getScore();
            count++;
        }
        //封装返回信息的类
        CommentRateVo commentRateVo = new CommentRateVo();

        if (count != 0) {
            String i = String.valueOf((score / count));
            commentRateVo.setRate(i);
        }else {
            commentRateVo.setRate(String.valueOf(NaN));
        }
        commentRateVo.setCommentList(comment);
        result.setCode(0);
        result.setData(commentRateVo);
        resp.getWriter().println(gson.toJson(result));
    }

    /**
     * @Author: 庄左
     * @Description: 通过id去查找问答表
     * @DateTime: 2022/7/3 23:47
     */
    private void getGoodsMsg(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));

        MessageServiceImpl messageService = new MessageServiceImpl();

        List<QuestionAnswerVo> messageVos = messageService.selectQuestionAnswerById(id);


        goodsResult.setCode(0);
        goodsResult.setData(messageVos);
        resp.getWriter().println(gson.toJson(goodsResult));

    }

    /**
     * @Author: 庄左
     * @Description: 根据id查询商品信息，包括他的规格信息，用与当用户点击商品时向其展示商品
     * @DateTime: 2022/7/3 23:10
     */
    private void getGoodsInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));

        GoodVo goodVo = goodsService.selectGoodByGoodsIdInMall(id);

        userResult.setCode(0);
        userResult.setData(goodVo);
        resp.getWriter().println(gson.toJson(userResult));
    }

    private void getGoodsByType(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer typeId = Integer.valueOf(req.getParameter("typeId"));
        List<GoodsMessageVo> goods = goodsService.selectGoodsByType(new Type(typeId, null));
        result.setCode(0);
        result.setData(goods);
        resp.getWriter().println(gson.toJson(result));
    }
}
